import axios from 'axios';
import io from 'socket.io-client';
import * as actionTypes from './actionTypes';
const socket = io('ws://localhost:9093');

const msgList = (chatList, users, userid) => ({
    type: actionTypes.MSG_LIST,
    chatList,
    users,
    userid
})

const recv = (msg, userid) => ({
    type: actionTypes.MSG_RECV,
    msg,
    userid
})

const msgRead = ({ from, userid, num}) => ({
    type: actionTypes.MSG_READ,
    from,
    userid,
    num
})

export const getMsgList = () => {
    return (dispatch, getState) => {
        axios.get('/user/get_chat_list').then((res) => {
            if (res.status === 200 && res.data.code === 0) {
                const userid = getState().toJS().user.user._id;
                dispatch(msgList(res.data.msgs, res.data.users, userid));
            }
        }).catch((err) => {});
    }
}

export const sendMsg = ({from, to, msg}) => {
    return (dispatch) => {
        socket.emit('sendChat', {from, to, msg});
    }
}

export const recvMsg = () => {
    return (dispatch, getState) => {
        socket.on('recvMsg', function(data) {
            const userid = getState().toJS().user.user._id;
            dispatch(recv(data, userid));
        });
    }
}

export const readMsg = (from) => {
    return (dispatch, getState) => {
        axios({
            method: 'post',
            url: '/user/readmsg',
            data: { from }
        }).then((res) => {
            const userid = getState().toJS().user.user._id;
            dispatch(msgRead({ from, userid, num:res.data.num}));
        })
    }
}